package server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

import remoteinfo.MetaInfo;
import remoteinfo.RemoteDbParse;
import remoteinfo.ResultSet;
public class Server implements Runnable{
	static int SerialNum = 0;
	Socket socket;
	public RemoteDbParse remotedbparse;
	public Server(Socket s){
		socket = s;
		remotedbparse=new RemoteDbParse();
	}
	
	public void run(){
		int myserialnum = SerialNum++;
		ResultSet rs;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			OutputStream output = socket.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(output);
			PrintWriter out = new PrintWriter(socket.getOutputStream());
			Scanner cin = new Scanner(System.in);
			String cmd;
			while(!(cmd = in.readLine()).equals("exit")){
				System.out.println("Receive from Client No."+myserialnum+":"+cmd);
				if(cmd.equals("metainfo")){
					List<MetaInfo> milist = remotedbparse.getMetaInfos();
					for(MetaInfo mi:milist){
						System.out.println(mi);
					}
					oos.writeObject(milist);
					oos.flush();
				}
				else{
					String[] ss = cmd.split(",");
					if(ss[0].equals("userlogin")){
						starDB.init("D:\\db\\"+ss[1]);
						oos.flush();
					}
					else{
						rs = remotedbparse.getResultSet(cmd);
						oos.writeObject(rs);
						oos.flush();
					}
				}

				
			}
			starDB.init("D:\\db\\stardbdata");
			System.out.println("The connection to Client NO."+myserialnum+" is closing...");
			in.close();
			cin.close();
			out.close();
			oos.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String args[]){
		int maxclient = 5;
		try{
			starDB.init("D:\\db\\stardbdata");
			ServerSocket server = new ServerSocket(5678);
			RemoteDbParse dbparse = new RemoteDbParse();
			dbparse.getResultSet("create table userinfo(username varchar(10) primary key,password varchar(10))");
			for(int i=0;i<maxclient;i++){
				Socket socket = server.accept();
				Thread t = new Thread(new Server(socket));
				t.start();
			}
			server.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
